﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Perceptron.Engine;

namespace Perceptron.WinSample
{
    public partial class MainView : Form
    {
        private readonly IEnumerable<ClassImage> _allObjects;
        private readonly Engine.Perceptron _perceptron;
        private readonly string[] _classes;

        public MainView()
        {
            InitializeComponent();

            _allObjects = ImageLoaderHelper.LoadObjects().ToList();

            InitUi();

            _perceptron = new Engine.Perceptron();
            _perceptron.Init();
            _perceptron.Teach(_allObjects);
            _classes = _allObjects.OrderBy(o => o.ClassId).Select(o => o.ClassName).Distinct().ToArray(); // TODO: remove heavy linq

            //foreach (var item in allObjects)
            //{
            //    var res = p.Classificate(item);
            //    var className = item.ClassName;
            //}
        }

        private void InitUi()
        {
            //_imagesBox.Items = _allObjects;
            foreach (var item in _allObjects)
                _imagesBox.Items.Add(item);

            _imagesBox.SelectedIndex = 0;

        }

        private void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            var selected = _imagesBox.SelectedItem as ClassImage;
            var bitmap = ImageLoaderHelper.ConvertToBitmap(selected.Object.Bytes, 16, 16);
            _sourceImageBox.Image = bitmap;

            if (_perceptron != null)
                NoiseValueChanged(sender, null);
        }

        private void NoiseValueChanged(object sender, EventArgs e)
        {
            var selected = _imagesBox.SelectedItem as ClassImage;
            byte[] noised = ImageLoaderHelper.AddNoise(selected.Object.Bytes, (double) _noiseNumericUpDown.Value);
            var bitmap = ImageLoaderHelper.ConvertToBitmap(noised, 16, 16);
            var res = _perceptron.Classificate(noised);

            _listBox.Items.Clear();

            for (int i = 0; i < res.Length; ++i)
            {
                _listBox.Items.Add(string.Format("{0:0.00}% ({1})", res[i]*100, _classes[i]));
                // _allObjects.Select(o => o.ClassId ==)
            }

            _noisedImageBox.Image = bitmap;
        }


    }
}
